<template>
  <view>
    <view class="main">
      <canvas
        v-show="load"
        @longpress.stop="saveSharePic"
        class="canvas"
        canvas-id="testCanvas"
        :style="{ height: `${deviation + 1300}rpx` }"
      ></canvas>
      <!-- <view class="down" @click="saveCanvas">
        <image src="/static/download.png" mode=""></image>
      </view> -->
      <view class="save" v-show="load">
        <view class="save-button" @click="saveCanvas">保存海报</view>
      </view>
    </view>
  </view>
</template>

<script>
import api from '@/request/api.js'
export default {
  onLoad(option) {
    this.id = option.id
    this.init()
  },
  data() {
    return {
      info: {}, // 藏品详情
      userInfo: {}, // 用户信息
      systemWidth: 0, // 屏幕高度比例
      id: '', // 藏品ID
      deviation: 0,
      load: false,
    }
  },
  methods: {
    async init() {
      const userInfo = uni.getStorageSync('userInfo')
      this.userInfo = userInfo
      const token = this.userInfo.token
      const uid = this.userInfo.uid
      const info = await api.myCollectionDetail({
        uid: uid,
        token: token,
        id: this.id, //用户唯一id
      })
      // 获取设备宽高
      uni.getSystemInfo({
        success: (system) => {
          this.systemWidth = system.windowWidth / 375
        },
      })
      this.info = info.data
      console.log('info', this.info)
      this.createdPoster()
    },
    // 保存canvas图片
    saveCanvas() {
      uni.canvasToTempFilePath({
        // 这里修改保存的图片格式
        fileType: 'jpg',
        canvasId: 'testCanvas',
        quality: 1,
        success: (res) => {
          // 保存带哦本地
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              uni.showToast({
                title: '保存海报成功',
                icon: 'none',
                duration: 3000,
              })
            },
            fail: () => {
              uni.showToast({
                title: '保存海报失败',
                icon: 'none',
                duration: 3000,
              })
            },
          })
        },
      })
    },
    // 长按保存海报
    saveSharePic() {
      uni.showModal({
        title: '提示',
        content: '确定要保存海报吗？',
        success: (res) => {
          if (res.confirm) {
            // canvas生成图片
            this.saveCanvas()
          }
        },
      })
    },
    // canvas 文字换行
    getTextInfo(canvas, str, size, width) {
      const getRpx = new Promise((resolve, reject) => {
        uni.getSystemInfo({
          success: (system) => {
            resolve(system.windowWidth / 375)
          },
        })
      })
      return getRpx.then((rpx) => {
        // 画布总宽度 rpx单位
        const canvasWidth = width * rpx
        // 字体大小 rpx单位
        let fontSize = parseInt(size * rpx)
        const tempArr = []
        for (let i = 0; i < str.length; i++) {
          const font = str.slice(i, i + 1)
          tempArr.push(font)
        }
        let rowFontNum = 0
        const totalStr = tempArr.reduce((now, next, index) => {
          const fontWidth = canvas.measureText(next).width * rpx
          now = now + fontWidth
          rowFontNum = canvasWidth > now ? index + 1 : rowFontNum
          return now
        }, 0)

        // 每行所需字数 = 画布总宽度 / 单个字体大小
        // let rowFontNum = Math.floor(canvasWidth / fontSize)

        // 字符串总长度
        let strLength = str.length
        // 所需行数 = 字符总长度 / 每行所需字数
        let rows = Math.ceil(strLength / rowFontNum)
        // 行高

        return { canvasWidth, fontSize, rowFontNum, strLength, rows, totalStr }
      })
    },

    // 生成海报
    async createdPoster() {
      uni.showLoading({
        title: '加载中',
        mask: true,
        icon: 'none',
      })
      const rpx = parseFloat(this.systemWidth.toFixed(2))
      const context = uni.createCanvasContext('testCanvas', this)
      // 背景色
      context.rect(0, 0, 650 * rpx, 1500 * rpx)
      context.setFillStyle('#000')
      context.fill()
      //   this.showState = true
      const code = new Promise((resolve, reject) => {
        // 二维码
        uni.downloadFile({
          url: 'https://publish.onedaen.com/uploads/material/picture/code.jpg',
          success: (res) => {
            context.drawImage(
              res.tempFilePath,
              20 * rpx,
              (556 + lineHeight) * rpx,
              75 * rpx,
              75 * rpx,
            )
            context.draw(true)
            resolve()
          },
        })
      })
      const imgs = new Promise((resolve, reject) => {
        // 商品主文件图
        uni.downloadFile({
          url: this.info.cover_url,
          success: (res) => {
            context.drawImage(res.tempFilePath, 0, 0, 325 * rpx, 313 * rpx)
            context.draw(true)
            resolve()
          },
        })
      })

      // 商品名称
      // context.setFontSize(18 * rpx)
      // context.setFillStyle('#fff')
      // context.fillText(this.info.name, 20 * rpx, 361 * rpx)

      const name = await this.getTextInfo(context, this.info.name, 18, 170)
      context.setFontSize(name.fontSize)
      context.setFillStyle('#fff')
      for (let i = 0; i <= name.rows; i++) {
        context.fillText(
          this.info.name.slice(name.rowFontNum * (i - 1), name.rowFontNum * i),
          20 * rpx,
          (341 + i * 20) * rpx,
        )
      }
      const lineHeight = (name.rows - 1) * 19
      this.deviation = lineHeight * 2
      // 拥有者和序号
      context.setFontSize(15 * rpx)
      context.setFillStyle('#ccc')
      context.fillText(
        `由${this.userInfo.nickName}拥有`,
        20 * rpx,
        (395 + lineHeight) * rpx,
      )
      // console.log('user', user)

      // const user = await this.getTextInfo(
      //   context,
      //   this.userInfo.nickName,
      //   15,
      //   650,
      // )
      // console.log('user', user)
      // context.setFontSize(15 * rpx)
      // context.setFillStyle('#ccc')
      // context.fillText(`由`, 20 * rpx, (395 + lineHeight) * rpx)
      // context.setFillStyle('#fff')
      // context.fillText(
      //   this.userInfo.nickName,
      //   35 * rpx,
      //   (395 + lineHeight) * rpx,
      // )
      // context.setFillStyle('#ccc')
      // context.fillText(
      //   '拥有',
      //   27 * rpx + user.totalStr,
      //   (395 + lineHeight) * rpx,
      // )
      // 边框
      context.beginPath()
      context.moveTo(234 * rpx, (lineHeight + 375) * rpx)
      context.arcTo(
        300 * rpx,
        (lineHeight + 375) * rpx,
        300 * rpx,
        (395 + lineHeight) * rpx,
        4 * rpx,
      )
      context.arcTo(
        300 * rpx,
        (395 + lineHeight) * rpx,
        230 * rpx,
        (395 + lineHeight) * rpx,
        4 * rpx,
      )
      context.arcTo(
        230 * rpx,
        (395 + lineHeight) * rpx,
        230 * rpx,
        (lineHeight + 375) * rpx,
        4 * rpx,
      )
      context.arcTo(
        230 * rpx,
        (lineHeight + 375) * rpx,
        300 * rpx,
        (lineHeight + 375) * rpx,
        4 * rpx,
      )
      context.setStrokeStyle('#4effff')
      context.stroke()
      context.setFontSize(12 * rpx)
      context.setFillStyle('#4effff')
      context.fillText(
        `序号#${this.info.serialNo}`,
        243 * rpx,
        (390 + lineHeight) * rpx,
      )
      // 发行信息
      context.setFontSize(12 * rpx)
      context.setFillStyle('#fff')
      context.fillText('发行方', 20 * rpx, (430 + lineHeight) * rpx)
      context.fillText('发行数量', 181 * rpx, (430 + lineHeight) * rpx)
      context.fillText('数字藏品ID', 20 * rpx, (456.5 + lineHeight) * rpx)
      context.fillText('长按识别', 115 * rpx, (590 + lineHeight) * rpx)
      context.fillText(
        '关注“卯时数字平台”了解更多',
        115 * rpx,
        (610 + lineHeight) * rpx,
      )

      context.setFillStyle('#ccc')
      context.fillText(this.info.brand_name, 75 * rpx, (430 + lineHeight) * rpx)
      context.fillText(
        this.info.show_number,
        249 * rpx,
        (430 + lineHeight) * rpx,
      )
      context.fillText(
        this.info.nft_id.substr(0, 43),
        20 * rpx,
        (482 + lineHeight) * rpx,
      )
      context.fillText(
        this.info.nft_id.substr(43),
        20 * rpx,
        (502 + lineHeight) * rpx,
      )
      // line
      context.beginPath()
      context.moveTo(20 * rpx, (530 + lineHeight) * rpx)
      context.lineTo(315 * rpx, (530 + lineHeight) * rpx)
      context.setStrokeStyle('#999999')
      context.stroke()
      context.draw(true)
      Promise.all([code, imgs]).then(() => {
        uni.hideLoading()
        this.load = true
      })
    },
  },
}
</script>

<style lang="scss">
.main {
  width: 750rpx;
  min-height: 100vh;

  background-color: #181816;
  overflow: hidden;
  // position: relative;
  .canvas {
    width: 650rpx;
    // height: 1500rpx;
    background-color: #000;
    margin: 0 auto;
  }
  .down {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    overflow: hidden;
    position: fixed;
    bottom: 60rpx;
    background-color: #000;
    right: 60rpx;
    // box-sizing: border-box;
    padding: 20rpx;
    border: 1rpx solid #fff;
    image {
      width: 100%;
      height: 100%;
    }
  }
  .save {
    width: 750rpx;
    .save-button {
      margin: 50rpx auto;
      width: 650rpx;
      height: 80rpx;
      background-color: #4effff;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #000;
      font-size: 30rpx;
      border-radius: 10rpx;
    }
  }
}
</style>
